package com.car.carmgr.controller;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class FileController {

    @RequestMapping("uploadFile")
    @ResponseBody
    public Map<String,Object> uploadFile(MultipartFile mf, HttpSession session){

        Map<String,Object> map=new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");

        // 1,得到老名字
        String oldName = mf.getOriginalFilename();
        // 2,得到tomcat里面的upload目录
        String realPath = session.getServletContext().getRealPath(
                "/static/images/");
        // 3,得到当前时间2018-07-14
        // 4,得到新的父目录的路径 并判断是否存在 如果不存在就创建
        String newRealPath =  "C:\\Users\\XBB\\Desktop\\carmgr\\src\\main\\resources\\static\\images";
        File parentFile = new File(newRealPath);
        if (!parentFile.exists()) {
            parentFile.mkdirs();// 创建文件夹
        }
        // 5,得到新名字
        String newName = oldName;
        // 6,构造文件
        File file = new File(parentFile, newName);
        // 7，上传
        try {
            mf.transferTo(file);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> data=new HashMap<>();
        //此处可修改保存路径格式
        data.put("src", "/car/static/images/"+newName);
        map.put("data", data);
        return map;
    }
}
